import React, { useState, useEffect } from 'react'
import { Button, Modal, Input, message, Popconfirm } from 'antd'
import { DeleteOutlined, PlusOutlined, DragOutlined } from '@ant-design/icons'
import { createResource, TreeNode } from '@designable/core'

const STORAGE_KEY = 'designable_blocks'

interface BlockMeta {
  id: string
  name: string
  schema: any
  createdAt: number
}

export const BlocksResourceWidget: React.FC = () => {
  const [blocks, setBlocks] = useState<BlockMeta[]>([])
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [blockName, setBlockName] = useState('')

  // 加载保存的区块
  useEffect(() => {
    const savedBlocks = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
    setBlocks(savedBlocks)
  }, [])

  // 删除区块
  const deleteBlock = (blockId: string) => {
    const updatedBlocks = blocks.filter((block) => block.id !== blockId)
    localStorage.setItem(STORAGE_KEY, JSON.stringify(updatedBlocks))
    setBlocks(updatedBlocks)
    message.success('区块删除成功')
  }

  // 清空所有区块
  const clearAllBlocks = () => {
    localStorage.removeItem(STORAGE_KEY)
    setBlocks([])
    message.success('所有区块已清空')
  }

  // 从schema创建TreeNode
  const createTreeNodeFromSchema = (schema: any): TreeNode => {
    const node = new TreeNode({
      componentName: schema.componentName || 'Field',
      props: schema.props || {},
      children: [],
    })

    // 递归处理子节点
    if (schema.children && Array.isArray(schema.children)) {
      schema.children.forEach((childSchema: any) => {
        const childNode = createTreeNodeFromSchema(childSchema)
        node.append(childNode)
      })
    }

    return node
  }

  // 创建区块资源
  const createBlockResource = (block: BlockMeta) => {
    // 创建区块的根节点
    const blockNode = createTreeNodeFromSchema(block.schema)

    // 创建资源
    return createResource({
      title: block.name,
      icon: 'Module',
      elements: [blockNode],
    })
  }

  return (
    <div style={{ padding: '8px' }}>
      <div
        style={{
          marginBottom: '12px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <span style={{ fontWeight: 'bold' }}>已保存的区块</span>
        <div>
          <Button
            type="text"
            size="small"
            icon={<PlusOutlined />}
            onClick={() => setIsModalVisible(true)}
            title="导入区块"
          />
          {blocks.length > 0 && (
            <Popconfirm
              title="确定要清空所有区块吗？"
              onConfirm={clearAllBlocks}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
                title="清空所有"
              />
            </Popconfirm>
          )}
        </div>
      </div>

      {blocks.length === 0 ? (
        <div style={{ textAlign: 'center', color: '#999', padding: '20px' }}>
          暂无保存的区块
        </div>
      ) : (
        <div
          style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(3, 1fr)',
            gap: '1px',
          }}
        >
          {blocks.map((block) => {
            const resources = createBlockResource(block)
            return resources.map((resource, index) => (
              <div
                key={`${block.id}-${index}`}
                className="dn-resource-item"
                style={{
                  padding: '8px',
                  border: '1px solid #d9d9d9',
                  borderRadius: '4px',
                  marginBottom: '8px',
                  cursor: 'grab',
                  backgroundColor: '#fafafa',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexDirection: 'column',
                  minHeight: '40px',
                }}
                data-designer-source-id={resource.node.id}
              >
                <DragOutlined style={{ marginBottom: '4px', color: '#999' }} />
                <span style={{ fontSize: '12px', textAlign: 'center' }}>
                  {block.name}
                </span>
                <div style={{ position: 'absolute', top: '4px', right: '4px' }}>
                  <Popconfirm
                    title="确定要删除这个区块吗？"
                    onConfirm={() => deleteBlock(block.id)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button
                      type="text"
                      size="small"
                      danger
                      icon={<DeleteOutlined />}
                      style={{ padding: '2px' }}
                    />
                  </Popconfirm>
                </div>
              </div>
            ))
          })}
        </div>
      )}

      <Modal
        title="导入区块"
        open={isModalVisible}
        onOk={() => {
          if (blockName.trim()) {
            // 这里可以添加导入区块的逻辑
            message.success('导入功能待实现')
            setIsModalVisible(false)
            setBlockName('')
          } else {
            message.error('请输入区块名称')
          }
        }}
        onCancel={() => {
          setIsModalVisible(false)
          setBlockName('')
        }}
      >
        <Input
          placeholder="请输入区块名称"
          value={blockName}
          onChange={(e) => setBlockName(e.target.value)}
        />
      </Modal>
    </div>
  )
}
